import { useEffect, useRef, useState } from "react";
import { useDropZone, useFileDialog } from '@reactuses/core'
import { cn } from "~/lib/utils";
import type { Route } from "./+types/drag-test";
import { useFetcher } from "react-router";
import { z } from 'zod'
import { Loader } from "lucide-react";

const formSchema = z.object({
  file: z.file().min(1, { message: "请选择文件" }).max(20 * 1024 * 1024, { message: "文件大小不能超过20MB" }),
  remark: z.string().min(1, { message: "请输入备注" })
})

export const action = async ({ request }: Route.ClientActionArgs) => {
  const formData = await request.formData()
  const file = formData.get("file") as File
  const remark = formData.get("remark") as string
  const result = formSchema.safeParse({ file, remark })
  console.log(remark, file);

  const formattedError = result.error?.flatten(i => {
    return i.message
  })

  if (!result.success) {
    return { error: formattedError?.fieldErrors }
  }

}
export default function DragTest(props: Route.ComponentProps) {

  const fileInputRef = useRef<HTMLInputElement>(null)
  const dropZoneRef = useRef<HTMLDivElement>(null)
  const [file, setFile] = useState<File>()
  const [dialogFileList, fileDialogOpen, resetFileDialog] = useFileDialog()
  useEffect(() => {
    if (dialogFileList?.length) {
      setFile(dialogFileList?.item(0)!)
      resetFileDialog()
    }
  }, [dialogFileList])
  const { Form, data, state } = useFetcher<{ error: Record<string, string[]> }>({
    key: "drag-test",
  })

  useEffect(() => {
    if (fileInputRef.current && file) {
      const dataTransfer = new DataTransfer()
      file && dataTransfer.items.add(file)
      fileInputRef.current.files = dataTransfer.files
    } else if (fileInputRef.current?.files?.length) {
      fileInputRef.current.files = null
    }
  }, [file])
  const isOver = useDropZone(dropZoneRef, (files) => {
    if (!files?.length) { return }

    setFile(files.at(0)!)
  })

  const isSubmitting = state === "submitting"
  return <div ref={dropZoneRef} className={cn("w-full h-screen flex flex-col justify-center", isOver && "bg-blue-500")}>
    <Form method="post" encType="multipart/form-data" className="flex flex-col items-center justify-center">
      <input ref={fileInputRef} type="file" className="hidden" name="file" id="file" />
      <p onClick={() => fileDialogOpen()}>{file?.name ? file.name : "选择文件"}</p>
      <div className="text-red-500">
        {data?.error ? data?.error?.file?.map((e, i) => <p key={i}>{e}</p>) : ''}
      </div>
      <label>
        备注
        <input type="text" name="remark" id="remark" />
      </label>
      <div className="text-red-500">
        {data?.error ? data?.error?.remark?.map((e, i) => <p key={i}>{e}</p>) : ''}
      </div>
      <button disabled={isSubmitting} type="submit">
        {isSubmitting && <Loader className="animate-spin" />}
        {isSubmitting ? "提交中..." : "提交"}
      </button>
    </Form>
  </div>;
}